package com.cicc.beergamevirtualsimulationsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cicc.beergamevirtualsimulationsystem.common.constant.EchartsConstant;
import com.cicc.beergamevirtualsimulationsystem.common.enums.userTypeEnum.RoleType;
import com.cicc.beergamevirtualsimulationsystem.common.enums.userTypeEnum.RoleTypeConfig;
import com.cicc.beergamevirtualsimulationsystem.common.exception.ExceptionFactory;
import com.cicc.beergamevirtualsimulationsystem.context.BaseContext;
import com.cicc.beergamevirtualsimulationsystem.entity.RecordEntity;
import com.cicc.beergamevirtualsimulationsystem.mapper.RecordMapper;
import com.cicc.beergamevirtualsimulationsystem.model.echarts.vo.EchartsVo;
import com.cicc.beergamevirtualsimulationsystem.service.EchartsService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Echarts数据展示
 *
 * @ClassName EchartsServiceImpl
 * @Description TODO
 * @Date 2024/11/6 13:22
 * @Version 1.0
 */

@Service
public class EchartsServiceImpl implements EchartsService {


    @Autowired
    private RecordMapper recordMapper;


    /**
     * 游戏结算界面柱状图数据展示
     *
     * @param roomId
     * @param userRole
     * @return
     */
    @Override
    public EchartsVo queryGameResult(String roomId, Integer userRole) {

        // 获取角色类型，根据传入的角色编码(userRole)查找对应的角色
        RoleType roleType = Arrays.stream(RoleType.values())
                .filter(role -> role.getCode().equals(userRole))  // 根据角色编码过滤角色
                .findFirst()  // 找到第一个符合条件的角色
                .orElseThrow(() -> ExceptionFactory.bizException("未知角色类型: " + userRole));  // 如果找不到对应角色，抛出异常
        if (userRole.equals(RoleType.CUSTOMER.getCode())) {
            // 创建 SeriesData 列表
            List<EchartsVo.SeriesData> seriesDataList = new ArrayList<>();
            List<RecordEntity> records = recordMapper.selectTotalOrderByRole(roomId);
            List<Function<RecordEntity, Integer>> fields = getFieldsBasedOnRecords(records);
            // 获取最大值和最小值
            Integer min = getValue(records, false,fields);
            Integer max = getValue(records, true,fields);
            EchartsVo echartsVo = new EchartsVo();
            // 提取username作为分类
            List<String> categories = records.stream()
                    .map(RecordEntity::getUserName) // 使用方法引用
                    .collect(Collectors.toList());
            // 为每个角色创建单独的系列数据
            for (RecordEntity record : records) {
                List<EchartsVo.DataWithLabel> labeledDataList = new ArrayList<>();
                int profit = (record.getProfit() != null) ? record.getProfit() : 0;
                int preReceiverTotalCost = (record.getPreReceiverTotalCost() != null) ? record.getPreReceiverTotalCost() : 0;
                int inventoryCost = (record.getInventoryCost() != null) ? record.getInventoryCost() : 0;
                int deferredDeliveryCost = (record.getDeferredDeliveryCost() != null) ? record.getDeferredDeliveryCost() : 0;

                // 将数据封装到 labeledDataList
                labeledDataList.add(new EchartsVo.DataWithLabel(EchartsConstant.SERIES_PROFIT, profit));
                labeledDataList.add(new EchartsVo.DataWithLabel(EchartsConstant.SERIES_PURCHASE_COST, preReceiverTotalCost));
                labeledDataList.add(new EchartsVo.DataWithLabel(EchartsConstant.SERIES_INVENTORY_COST, inventoryCost));
                labeledDataList.add(new EchartsVo.DataWithLabel(EchartsConstant.SERIES_DEFERRED_DELIVERY_COST, deferredDeliveryCost));
                // 创建 SeriesData 并添加到 seriesDataList
                seriesDataList.add(createSeriesData(record.getUserName(), labeledDataList));
            }
            echartsVo.setCategories(categories);
            echartsVo.setSeries(seriesDataList);
            echartsVo.setMaxValue(max);
            echartsVo.setMinValue(min);
            return echartsVo;
        }

        // 配置查询条件，构建查询 RecordEntity 的条件
        LambdaQueryWrapper<RecordEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RecordEntity::getRoomId, roomId)
                .eq(RecordEntity::getUserId, BaseContext.getCurrentId())
                .eq(RecordEntity::getUserRole, userRole)
                .select(RecordEntity::getPeriod,
                        RecordEntity::getPreReceiverTotalCost,
                        RecordEntity::getInventoryCost,
                        RecordEntity::getDeferredDeliveryCost)
                .orderByAsc(RecordEntity::getPeriod);
        // 查询记录
        List<RecordEntity> records = recordMapper.selectList(queryWrapper);
        List<Function<RecordEntity, Integer>> fields = getFieldsBasedOnRecords(records);
        // 获取最大值和最小值
        Integer min = getValue(records, false,fields);
        Integer max = getValue(records, true,fields);

        // 获取角色对应的 SeriesData 配置，RoleTypeConfig根据角色类型来获取不同的图表数据系列
        RoleTypeConfig config = RoleTypeConfig.valueOf(roleType.name());
        List<EchartsVo.SeriesData> seriesDataList = config.getSeriesData();  // 获取角色对应的系列数据
        // 初始化图表数据对象
        EchartsVo chartData = new EchartsVo();
        List<String> categories = new ArrayList<>();
        // 填充数据
        for (RecordEntity record : records) {
            categories.add(record.getPeriod().toString());
            seriesDataList.get(0).getData().add(record.getPreReceiverTotalCost());  // 填充订单成本数据
            seriesDataList.get(1).getData().add(record.getInventoryCost());  // 填充库存成本数据
            seriesDataList.get(2).getData().add(record.getDeferredDeliveryCost());  // 填充延期交货成本数据
        }
        // 设置图表数据的 X 轴和 Y 轴标题
        chartData.setCategories(categories);  // 设置图表的 X 轴数据
        chartData.setSeries(seriesDataList);  // 设置图表的系列数据（订单成本、库存成本、延期交货成本）
        chartData.setXTitle(EchartsConstant.X_AXIS_PERIOD);  // 设置 X 轴标题为周期
        chartData.setYTitle(EchartsConstant.Y_AXIS_AMOUNT);  // 设置 Y 轴标题为金额
        chartData.setMaxValue(max);
        chartData.setMinValue(min);
        return chartData;
    }




    /**
     * 取最大最小
     *
     * @return
     */
    public Integer getValue(List<RecordEntity> records, Boolean isMax, List<Function<RecordEntity, Integer>> fields) {
        int value = 0;
        // 获取比较函数，选择最大或最小值
        Comparator<RecordEntity> comparator = Comparator.comparing(record -> {
            // 计算每个记录的字段的最大或最小值
            int result = fields.stream()
                    .mapToInt(field -> {
                        Integer fieldValue = field.apply(record);
                        return (fieldValue != null) ? fieldValue : 0;  // 确保不会返回 null
                    })
                    .reduce(isMax ? Integer::max : Integer::min)  // 这里的 reduce 要有一个合适的初始值
                    .orElse(0);  // 如果没有字段值，返回 0
            return result;
        });

        // 获取目标记录（最大值或最小值）
        Optional<RecordEntity> targetRecord = records.stream().max(comparator);

        // 设置目标值
        if (targetRecord.isPresent()) {
            RecordEntity record = targetRecord.get();
            // 计算目标记录的最终值（最大或最小）
            value = fields.stream()
                    .mapToInt(field -> {
                        Integer fieldValue = field.apply(record);
                        return (fieldValue != null) ? fieldValue : 0;  // 确保不会返回 null
                    })
                    .reduce(isMax ? Integer::max : Integer::min)
                    .orElse(0);  // 如果没有字段值，返回 0
        }

        // 如果 isMax 为 false，表示需要选最大负数，选绝对值最大
        if (!isMax) {
            // 找出最大的负数（绝对值最大）
            value = records.stream()
                    .map(record -> fields.stream()
                            .mapToInt(field -> {
                                Integer fieldValue = field.apply(record);
                                return (fieldValue != null) ? fieldValue : 0;  // 确保不会返回 null
                            })
                            .reduce(Integer::min)  // 选出每个记录的最小值
                            .orElse(0)) //
                    .filter(val -> val < 0) // 过滤负数
                    .max(Comparator.comparingInt(Math::abs)) // 按绝对值大小选最大负数
                    .orElse(0); // 如果没有负数，返回 0
        }

         return (int) Math.ceil(value * 1.2);

    }


    public List<Function<RecordEntity, Integer>> getFieldsBasedOnRecords(List<RecordEntity> records) {
        List<Function<RecordEntity, Integer>> fields = new ArrayList<>();

        Method[] methods = RecordEntity.class.getDeclaredMethods();

        for (Method method : methods) {
            if (method.getName().startsWith("get") && method.getReturnType() == Integer.class) {
                // 通过反射获取 getter 方法并添加到字段列表中
                try {
                    String methodName = method.getName();
                    Method getterMethod = RecordEntity.class.getMethod(methodName);
                    Function<RecordEntity, Integer> function = (record) -> {
                        try {
                            return (Integer) getterMethod.invoke(record);
                        } catch (Exception e) {
                            e.printStackTrace();
                            return 0;  // 出错时返回默认值
                        }
                    };
                    fields.add(function);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }
        }

        return fields;
    }


    /**
     * 游戏结算界面折线图数据
     *
     * @param roomId
     * @param userRole
     * @return
     */
    @Override
    public EchartsVo queryGameResultByRoomId(String roomId, Integer userRole) {
        if (userRole.equals(RoleType.CUSTOMER.getCode())) {
            // 查询记录数据
            List<RecordEntity> record = recordMapper.selectAggregatedData(roomId);
            // 获取角色名称
            List<String> userName = record.stream()
                    .map(RecordEntity::getUserName)
                    .distinct().toList();
            List<String> period = record.stream()
                    .map(v -> v.getPeriod().toString())
                    .distinct().toList();
            // 创建 EchartsVo 对象
            EchartsVo echartsVo = new EchartsVo();
            echartsVo.setTotalRole(userName);
            ArrayList<EchartsVo.SeriesData> data = new ArrayList<>();
            // 对每个角色调用 getDataForRoleAndCategory 方法来获取数据
            for (String role : userName) {
                List<EchartsVo.SeriesData> seriesData = getDataForRoleAndCategory(role, record);
                data.addAll(seriesData);
            }
            echartsVo.setSeries(data);
            echartsVo.setCategories(period);
            echartsVo.setYTitle(EchartsConstant.Y_AXIS_NUMBER);
            // 返回处理后的 EchartsVo 对象
            return echartsVo;
        }
        LambdaQueryWrapper<RecordEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RecordEntity::getRoomId, roomId)
                .eq(RecordEntity::getUserId, BaseContext.getCurrentId())
                .eq(RecordEntity::getUserRole, userRole)
                .select(RecordEntity::getPeriod, RecordEntity::getProfit, RecordEntity::getDeliverTotal)
                .orderByAsc(RecordEntity::getPeriod);  // 确保按 period 排序
        // 获取数据
        List<RecordEntity> records = recordMapper.selectList(queryWrapper);
        String userId = BaseContext.getCurrentId();
        Integer i = recordMapper.selectProfit(roomId,userId , userRole);
        // 初始化返回对象
        EchartsVo chartData = new EchartsVo();
        List<String> categories = new ArrayList<>();
        List<EchartsVo.SeriesData> seriesDataList = new ArrayList<>();
        // 使用策略模式创建数据系列
        seriesDataList.add(createSeriesData(EchartsConstant.Y_AXIS_PROFIT, 0, records, categories, RecordEntity::getProfit));
        seriesDataList.add(createSeriesData(EchartsConstant.SERIES_DELIVER_TOTAL, 1, records, categories, RecordEntity::getDeliverTotal));
        // 设置图表数据
        chartData.setCategories(categories);
        chartData.setSeries(seriesDataList);
        chartData.setProfit(i);
        // 设置图表的额外配置
        EchartsVo.ChartOptions chartOptions = createChartOptions();
        chartData.setChartOptions(chartOptions);
        return chartData;
    }


    /**
     * 主持人游戏界面展示全部玩家的利润数据 (折线)
     */
    @Override
    public EchartsVo queryAllPlayerProfit(String roomId, Integer userRole) {
        if (!userRole.equals(RoleType.CUSTOMER.getCode())) {
            throw ExceptionFactory.bizException("角色类型不匹配，无法查询数据: " + userRole);
        }
        List<RecordEntity> recordEntities = recordMapper.selectAllPlayerProfit(roomId);
        List<EchartsVo.DataWithLabel> labeledDataList = new ArrayList<>();
        for (RecordEntity recordEntity : recordEntities) {
            String userName = recordEntity.getUserName();
            Integer profit = recordEntity.getProfit();
            EchartsVo.DataWithLabel dataWithLabel = new EchartsVo.DataWithLabel(userName, profit);
            labeledDataList.add(dataWithLabel);
        }
        EchartsVo.SeriesData seriesData = new EchartsVo.SeriesData();
        seriesData.setDataLabels(labeledDataList);
        EchartsVo echartsVo = new EchartsVo();
        List<EchartsVo.SeriesData> seriesList = new ArrayList<>();
        seriesList.add(seriesData);
        echartsVo.setSeries(seriesList);
        echartsVo.setYTitle(EchartsConstant.Y_AXIS_AMOUNT);
        return echartsVo;
    }


    /**
     * 游戏局中玩家的数据展示（柱状）
     *
     * @param roomId
     * @param playerId
     * @param userRole
     * @return
     */
    @Override
    public EchartsVo queryPlayerData(String roomId, Integer playerId, Integer userRole) {
        RoleType roleType = Arrays.stream(RoleType.values())
                .filter(role -> role.getCode().equals(userRole))  // 根据角色编码过滤角色
                .findFirst()  // 找到第一个符合条件的角色
                .orElseThrow(() -> ExceptionFactory.bizException("未知角色类型: " + userRole));  // 如果找不到对应角色，抛出异常
        // 配置查询条件，构建查询 RecordEntity 的条件
        LambdaQueryWrapper<RecordEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RecordEntity::getRoomId, roomId)
                .eq(RecordEntity::getUserId, BaseContext.getCurrentId())
                .eq(RecordEntity::getUserRole, userRole)
                .eq(RecordEntity::getPeriod, playerId)
                .select(
                        RecordEntity::getProfit,
                        RecordEntity::getPreReceiverTotalCost,
                        RecordEntity::getInventoryCost,
                        RecordEntity::getDeferredDeliveryCost);
        // 查询记录
        List<RecordEntity> records = recordMapper.selectList(queryWrapper);
        List<Function<RecordEntity, Integer>> fields = getFieldsBasedOnRecords(records);;
        // 获取最大值和最小值
        Integer min = getValue(records, false,fields);
        Integer max = getValue(records, true,fields);
        // 获取角色对应的 SeriesData 配置，RoleTypeConfig 根据角色类型来获取不同的图表数据系列
        RoleTypeConfig config = RoleTypeConfig.valueOf(roleType.name());
        List<EchartsVo.SeriesData> seriesDataList = config.overallData();  // 获取角色对应的系列数据
        List<String> names = seriesDataList.stream()
                .map(EchartsVo.SeriesData::getName)
                .collect(Collectors.toList());
        // 初始化图表数据对象
        EchartsVo chartData = new EchartsVo();
        chartData.setCategories(names);

        // 填充数据
        for (RecordEntity record : records) {
            seriesDataList.get(0).getData().add(record.getProfit());  // 利润
            seriesDataList.get(1).getData().add(record.getPreReceiverTotalCost());  // 订单成本数据
            seriesDataList.get(2).getData().add(record.getInventoryCost());  // 库存成本数据
            seriesDataList.get(3).getData().add(record.getDeferredDeliveryCost());  // 延期交货成本数据
        }
        chartData.setSeries(seriesDataList);
        chartData.setYTitle(EchartsConstant.Y_AXIS_AMOUNT);
        chartData.setMaxValue(max);
        chartData.setMinValue(min);
        return chartData;

    }


    /**
     * 局中玩家供给数据展示（柱状）
     *
     * @param roomId
     * @param playerId
     * @param userRole
     * @return
     */
    @Override
    public EchartsVo queryPlayerSupplyData(String roomId, Integer playerId, Integer userRole) {
        RoleType roleType = Arrays.stream(RoleType.values())
                .filter(role -> role.getCode().equals(userRole))  // 根据角色编码过滤角色
                .findFirst()  // 找到第一个符合条件的角色
                .orElseThrow(() -> ExceptionFactory.bizException("未知角色类型: " + userRole));  // 如果找不到对应角色，抛出异常
        // 配置查询条件，构建查询 RecordEntity 的条件
        LambdaQueryWrapper<RecordEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RecordEntity::getRoomId, roomId)
                .eq(RecordEntity::getUserId, BaseContext.getCurrentId())
                .eq(RecordEntity::getUserRole, userRole)
                .eq(RecordEntity::getPeriod, playerId)
                .select(
                        RecordEntity::getReceiverTotal,
                        RecordEntity::getUpStreamOweTotal);

        // 查询记录
        List<RecordEntity> records = recordMapper.selectList(queryWrapper);
        List<Function<RecordEntity, Integer>> fields = getFieldsBasedOnRecords(records);
        // 获取最大值和最小值
        Integer min = getValue(records, false,fields);
        Integer max = getValue(records, true,fields);
        // 创建 oweSeriesData 和 deliverSeriesData
        EchartsVo.SeriesData oweSeriesData = new EchartsVo.SeriesData();
        List<Integer> oweTotals = new ArrayList<>();
        for (RecordEntity record : records) {
            oweTotals.add(record.getUpStreamOweTotal());
        }
        oweSeriesData.setData(oweTotals);
        oweSeriesData.setName(EchartsConstant.UP_STREAM_OWE_TOTAL);
        EchartsVo.SeriesData deliverSeriesData = new EchartsVo.SeriesData();
        List<Integer> deliverTotals = new ArrayList<>();
        for (RecordEntity record : records) {
            deliverTotals.add(record.getReceiverTotal());
        }
        deliverSeriesData.setData(deliverTotals);
        deliverSeriesData.setName(EchartsConstant.UP_STREAM_DELIVER_TOTAL);

        // 将 oweSeriesData 和 deliverSeriesData 放到 data 中
        EchartsVo data = new EchartsVo();
        data.setYTitle(EchartsConstant.Y_AXIS_NUMBER);
        data.setSeries(Arrays.asList(deliverSeriesData, oweSeriesData));

        ArrayList<String> categories = new ArrayList<>();
        categories.add(deliverSeriesData.getName());
        categories.add(oweSeriesData.getName());
        data.setCategories(categories);
        data.setMaxValue(max);
        data.setMinValue(min);
        return data;

    }

    /**
     * 主持人局中游戏的数据展示
     *
     * @param roomId
     * @param playerId
     * @return
     */
    @Override
    public EchartsVo queryPlayerDataByRoomId(String roomId, Integer playerId) {
        LambdaQueryWrapper<RecordEntity> recordEntityQueryWrapper = new LambdaQueryWrapper<>();
        recordEntityQueryWrapper.eq(RecordEntity::getRoomId, roomId)
                .eq(RecordEntity::getUserRole, RoleType.RETAILER.getCode())
                .eq(RecordEntity::getPeriod, playerId)
                .select(RecordEntity::getUserName, RecordEntity::getDeliverTotal, RecordEntity::getAccumulateOweTotal);
        // 查询记录列表
        List<RecordEntity> recordEntities = recordMapper.selectList(recordEntityQueryWrapper);
        List<Function<RecordEntity, Integer>> fields = getFieldsBasedOnRecords(recordEntities);
        // 获取最大值和最小值
        Integer min = getValue(recordEntities, false,fields);
        Integer max = getValue(recordEntities, true,fields);
        // 用来存储所有的 SeriesData
        List<EchartsVo.SeriesData> seriesDataList = new ArrayList<>();
        // 遍历记录列表，生成每个用户的 SeriesData
        for (RecordEntity recordEntity : recordEntities) {
            EchartsVo.SeriesData seriesData = new EchartsVo.SeriesData();
            seriesData.setName(recordEntity.getUserName());
            // 存储该用户的数据
            List<EchartsVo.DataWithLabel> labeledDataList = new ArrayList<>();
            EchartsVo.DataWithLabel deliverData = new EchartsVo.DataWithLabel();
            deliverData.setLabel(EchartsConstant.OWE_TOTAL);
            deliverData.setValue(recordEntity.getDeliverTotal());
            labeledDataList.add(deliverData);
            EchartsVo.DataWithLabel oweData = new EchartsVo.DataWithLabel();
            oweData.setLabel(EchartsConstant.SERIES_OWE_RETAILER_TOTAL);
            oweData.setValue(recordEntity.getAccumulateOweTotal());
            labeledDataList.add(oweData);
            // 设置该用户的所有数据标签
            seriesData.setDataLabels(labeledDataList);
            seriesDataList.add(seriesData);
        }
        EchartsVo echartsVo = new EchartsVo();
        echartsVo.setYTitle(EchartsConstant.Y_AXIS_NUMBER);
        echartsVo.setSeries(seriesDataList);
        echartsVo.setMaxValue(max);
        echartsVo.setMinValue(min);
        return echartsVo;
    }


    /**
     * 创建图表额外配置
     */
// 创建 Echarts 图表的配置对象，包括 X 轴和多个 Y 轴的设置
    private EchartsVo.ChartOptions createChartOptions() {
        // 创建图表配置对象
        EchartsVo.ChartOptions chartOptions = new EchartsVo.ChartOptions();
        // 设置 X 轴配置，X 轴显示的标题、数据单位和对应的 Y 轴
        chartOptions.setxAxis(new EchartsVo.Axis(EchartsConstant.X_AXIS_PERIOD, EchartsConstant.Y_AXIS_LEFT, EchartsConstant.Y_AXIS_UNIT));
        // 设置 Y 轴配置，包含两个 Y 轴，一个在左边显示利润，另一个在右边显示交付总数
        chartOptions.setyAxisList(Arrays.asList(
                // 左侧 Y 轴，显示利润，单位为金额
                new EchartsVo.Axis(EchartsConstant.Y_AXIS_PROFIT, EchartsConstant.Y_AXIS_LEFT, EchartsConstant.Y_AXIS_AMOUNT),
                // 右侧 Y 轴，显示交付总数
                new EchartsVo.Axis(EchartsConstant.SERIES_DELIVER_TOTAL, EchartsConstant.Y_AXIS_RIGHT, EchartsConstant.Y_AXIS_DELIVER_TOTAL)
        ));
        return chartOptions;
    }

    /**
     * 创建数据系列的通用方法，用于处理不同的业务数据，并为每个系列提供数据。
     *
     * @param name          数据系列的名称，例如“利润”或“交付总数”
     * @param index         数据系列的索引，用于在图表中区分不同的系列
     * @param records       查询到的记录数据
     * @param categories    存储周期（period）的列表，避免重复添加
     * @param dataExtractor 提供提取数据的方法，用于从每个记录中获取需要的数据（例如利润或交付总数）
     * @return 返回填充好的 Echarts 数据系列
     */
    private EchartsVo.SeriesData createSeriesData(String name, int index, List<RecordEntity> records,
                                                  List<String> categories, Function<RecordEntity, Integer> dataExtractor) {
        // 创建一个新的 SeriesData 对象
        EchartsVo.SeriesData seriesData = new EchartsVo.SeriesData();
        seriesData.setName(name);  // 设置数据系列的名称（例如：利润、交付总数）
        seriesData.setIndex(index);  // 设置数据系列的索引（在图表中用于区分不同的系列）
        seriesData.setData(new ArrayList<>());  // 初始化数据列表，用于存放每个数据点
        // 遍历所有记录数据，提取相关数据
        for (RecordEntity record : records) {
            String period = record.getPeriod().toString();  // 获取记录的周期（period）
            // 如果周期不在类别列表中，添加到类别列表中（避免重复）
            if (!categories.contains(period)) {
                categories.add(period);
            }
            // 提取记录中的数据，并将其添加到数据系列中
            seriesData.getData().add(dataExtractor.apply(record));
        }
        return seriesData;
    }


    // 创建 SeriesData 的简化方法
    private EchartsVo.SeriesData createSeriesData(String userName, List<EchartsVo.DataWithLabel> labeledDataList) {
        EchartsVo.SeriesData seriesData = new EchartsVo.SeriesData();
        seriesData.setName(userName);  // 使用角色名称作为数据系列名称
        seriesData.setDataLabels(labeledDataList); // 设置带标签的数据
        return seriesData;
    }


    // 获取某个角色在某个周期的数据值
    private List<EchartsVo.SeriesData> getDataForRoleAndCategory(String role, List<RecordEntity> record) {
        // 用于存储最终的SeriesData
        Map<String, EchartsVo.SeriesData> seriesDataMap = new LinkedHashMap<>();
        // 遍历记录列
        for (RecordEntity data : record) {
            String userName = data.getUserName();
            // 判断是否符合角色条件
            if (role.equals(userName)) {
                Integer preReceiverTotal = data.getPreReceiverTotal();
                Integer oweTotalList = data.getDeliverTotal();
                // 处理订货量
                addDataToSeriesMap(seriesDataMap, userName, EchartsConstant.TOTAL_ORDER, EchartsConstant.ORDER_IDENTIFIER, preReceiverTotal);
                // 处理发货量
                addDataToSeriesMap(seriesDataMap, userName, EchartsConstant.OWE_TOTAL, EchartsConstant.DELIVER_IDENTIFIER, oweTotalList);
            }
        }
        return new ArrayList<>(seriesDataMap.values());
    }

    private void addDataToSeriesMap(Map<String, EchartsVo.SeriesData> seriesDataMap, String userName, String operation, String identification, Integer value) {
        // 将 name 和 operation 拼接在一起作为 key
        String key = userName + operation;

        // 如果 Map 中没有该 key，创建一个新的 SeriesData 对象，并添加数据
        seriesDataMap.computeIfAbsent(key, k -> {
            EchartsVo.SeriesData seriesData = new EchartsVo.SeriesData();
            seriesData.setName(userName); // 设置名称为用户名称
//            seriesData.setOperation(operation); // 设置操作类型
            seriesData.setIdentifier(identification);
            seriesData.setName(userName + operation);
            seriesData.setData(new ArrayList<>()); // 初始化数据列表
            return seriesData;
        }).getData().add(value); // 在 SeriesData 的数据列表中添加新值
    }


}
